// pages/shoppingMall/evaluate.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "评价", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent'
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    btnText: '提交',
    noteMaxLen: 300,
    partPro: '',
    updataList: [], // 图片列表 
    evaluateLevel: [{
      id: 1,
      level: 1,
      name: "好评"
    }, {
      id: 2,
      level: 2,
      name: "中评"
    }, {
      id: 3,
      level: 3,
      name: "差评"
    }],
    evaluateLevelId: -1,
    isAnonymous: false,
    shareTitle: '',
    shareImg: '',
    openid: '',
    orderId: 0,
    isEdit: 0,
    imgMax: 0,
    imgUpNum: 0,
    serviceImgPath: [],
    flag: 0
  },
  tel() {
    wx.makePhoneCall({
      phoneNumber: '023-81395565',
    })
  },
  //评价
  partPro: function (e) {
    var value = e.detail.value,
      len = parseInt(value.length);
    if (len > this.data.noteMaxLen) return;
    this.setData({
      partPro: value,
      currentNoteLen: len //当前字数
    })
  },
  getLocalityImg() {
    let that = this;
    wx.chooseImage({
      count: that.data.imgUpNum,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFiles = res.tempFiles
        let answer = tempFiles.every(item => {
          return item.size <= parseInt(that.data.imgMax) * 1024 * 1024
        })
        if (answer) {
          const addpic = res.tempFiles.map(el => el.path)
          that.setData({
            updataList: [...that.data.updataList, ...addpic]
          })
        } else {
          app.showTip("上传图片不能大于" + that.data.imgMax + "M哦");
        }
      }
    })
  },
  //删除照片功能与预览照片功能 
  deleteImg(e) {
    let img_arr = this.data.updataList;
    let serviceImgPath = this.data.serviceImgPath;
    let index = e.currentTarget.dataset.index;
    var newImgArr = [];
    var newServiceImgPath = [];
    for (var i = 0; i < img_arr.length; i++) {
      if (i != index) {
        newImgArr.push(img_arr[i]);
      }
    }
    for (var j = 0; j < serviceImgPath.length; j++) {
      if (j != index) {
        newServiceImgPath.push(serviceImgPath[j]);
      }
    }
    this.setData({
      updataList: newImgArr,
      serviceImgPath: newServiceImgPath
    });
  },
  //预览图片
  previewImg(e) {
    let index = e.currentTarget.dataset.index;
    let img_arr = this.data.updataList;
    wx.previewImage({
      current: img_arr[index],
      urls: img_arr
    })
  },
  anonymous() {
    let that = this;
    that.setData({
      isAnonymous: !that.data.isAnonymous
    })
  },
  evaluateLevel(e) {
    let that = this;
    let id = e.currentTarget.dataset.id;
    that.setData({
      evaluateLevelId: id
    })
  },
  //提交评价
  tj() {
    var that = this;
    var partPro = that.data.partPro;
    var evaluateLevelId = that.data.evaluateLevelId;
    if (partPro == "") {
      app.showTip("请填写评价内容");
      return;
    } else if (evaluateLevelId == -1) {
      app.showTip("请选择评价等级");
      return;
    } else {
      //判断是否上传了图片
      if (that.data.updataList.length > 0) {
        //上传了图片 先保存图片
        wx.showLoading({
          title: '照片上传中...',
          mask: true
        });

        for (var row = 0; row < that.data.updataList.length; row++) {
          var urlStr = that.data.updataList[row].substring(0, 5);
          if (urlStr == 'https') {
            if (row == (that.data.updataList.length-1)) {
              wx.hideLoading();
              that.sub();
            } else {
              continue;
            }
          }
          wx.uploadFile({
            url: that.data.baseUrl + "uploadsShopCommentImg.php", //服务器接口
            method: 'POST',
            filePath: that.data.updataList[row],
            header: {
              'content-type': 'multipart/form-data'
            },
            name: 'file', //服务器定义的Key值
            formData: {},
            success: function (res) {
              //wx.hideLoading();
              console.log(res.data);
              if (res.data) {
                var serviceImgPath = that.data.serviceImgPath;
                serviceImgPath.push(res.data);
                that.setData({
                  serviceImgPath: serviceImgPath
                });

                if (that.data.updataList.length == serviceImgPath.length) {
                  //调用最终上传数据
                  wx.hideLoading();
                  that.sub();
                }
              } else {
                app.showTip('服务器保存图片失败,请刷新页面重试');
              }
            },
            fail: function () {
              wx.hideLoading();
              app.showTip('服务器繁忙,请稍候重试');
            }
          });
        }
      } else {
        //未上传图片
        that.sub();
      }
    }
  },

  //提交最终数据
  sub() {
    var that = this;
    wx.showLoading({
      title: '信息提交中...',
      mask: true
    });

    var partPro = that.data.partPro;
    var evaluateLevelId = that.data.evaluateLevelId;
    var isNm = 0;
    if (that.data.isAnonymous) {
      isNm = 1;
    }

    if (that.data.flag == 0) {
      that.setData({
        flag: 1
      });

      wx.request({
        url: that.data.baseUrl + 'addOrEditShopCommentInfo.php',
        method: 'POST',
        data: {
          'openid': that.data.openid,
          'orderId': that.data.orderId,
          'imgArr': JSON.stringify(that.data.serviceImgPath),
          'comment': partPro,
          'commentGrade': evaluateLevelId,
          'isNm': isNm,
          'isEdit': that.data.isEdit
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          wx.hideLoading();
          app.showTip(res.data.msg);
          if (res.data.status == 1) {
            //重新加载数据
            setTimeout(function () {
              wx.navigateBack({
                delta: 1
              });
            }, 1300);
          } else {
            that.setData({
              flag: 0
            });
          }
        },
        fail: function () {
          wx.hideLoading();
          that.setData({
            flag: 0
          });
          app.showTip('抱歉,服务器繁忙');
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    var orderId = options.smallOrderId;
    var isEdit = options.isEdit;
    if (orderId == '' || orderId == null || orderId == undefined) {
      app.showTip('未获取到订单ID哦');
      setTimeout(function () {
        wx.navigateBack({
          delta: 1
        });
      }, 1300)
      return;
    } else {
      that.setData({
        orderId: orderId,
        isEdit: isEdit
      });
    }

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getShopCommentPageInfo(res.data.openid, orderId, isEdit);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getShopCommentPageInfo(openid, orderId, isEdit);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本页数据
  getShopCommentPageInfo(openid, orderId, isEdit) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    })
    wx.request({
      url: that.data.baseUrl + 'getShopCommentPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid,
        'orderId': orderId,
        'isEdit': isEdit
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //重新赋值后台请求数据
          if (isEdit == 1) {
            //编辑
            var commentInfo = res.data.commentInfo;
            that.setData({
              imgMax: res.data.upImgSize,
              imgUpNum: res.data.upImgNum,
              evaluateLevelId: commentInfo.commentGrade,
              isAnonymous: parseInt(commentInfo.isNm),
              partPro: commentInfo.comment,
              updataList: commentInfo.imgList, // 图片列表 
              serviceImgPath: commentInfo.imgList
            });

            //处理已输入的文字个数
            var len = parseInt(commentInfo.comment.length);
            if (len > that.data.noteMaxLen) return;
            that.setData({
              currentNoteLen: len //当前字数
            });
          } else {
            //添加
            that.setData({
              imgMax: res.data.upImgSize,
              imgUpNum: res.data.upImgNum
            })
          }
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        }
      },
      fail: function () {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/index/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})